package com.tanhua.sso.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.common.pojo.User;
import com.tanhua.sso.mapper.UserMapper;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by 景银泰
 * date 2020-11-10 18:08
 * Description :
 * Version :
 */
@Service
public class UserService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Value("${jwt.secret}")
    private String secret;

    @Autowired
    private HuanXinService huanXinService;


    private static final ObjectMapper MAPPER = new ObjectMapper();


    private static final Logger LOGGER = LoggerFactory.getLogger(UserService.class);

    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    public String login(String mobile, String code) {
        String redisKey = "CHECK_CODE_" + mobile;
        String value = redisTemplate.opsForValue().get(redisKey);
        System.out.println("获取redis:" + value);
        if (StringUtils.isEmpty(value)) {
            System.out.println("验证码失效");
            //验证码失效
            return null;
        }


        if (!code.equalsIgnoreCase(value)) {
            System.out.println("验证码输入错误!");

            //验证码输入错误！
            return null;
        }


        Boolean isNew = false; //默认已经注册！

        //检验改手机号是否已经注册，如果没有注册，需要注册一个手机号，如果注册了 ，直接登录
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", mobile);
        User user = this.userMapper.selectOne(queryWrapper);

        if (null == user) {
            //如果手机号没有注册！
            user = new User();
            user.setMobile(mobile);
            //设置默认密码
            user.setPassword(DigestUtils.md5Hex("123456"));
            this.userMapper.insert(user);

            isNew = true;

            this.huanXinService.register(user.getId());
        }

        Map<String, Object> claims = new HashMap<>();

        claims.put("mobile", mobile);
        claims.put("id", user.getId());
        //生成token
        String token = Jwts.builder()
                .setClaims(claims) //设置相应媒体
                .signWith(SignatureAlgorithm.HS256, secret)  //设置加密方法和加密名字
                .compact();

        try {
            //将token存放到redis中
            String redisTokenKey = "TOKEN_" + token;
            String redisTokenValue = MAPPER.writeValueAsString(user);

            this.redisTemplate.opsForValue().set(redisTokenKey, redisTokenValue, Duration.ofHours(1));
        } catch (Exception e) {
            LOGGER.error("存储token出错！", e);
        }


        try {
            //发送RocketMQ消息
            Map<String, Object> msg = new HashMap<>();
            msg.put("id", user.getId());
            msg.put("mobile", mobile);
            msg.put("date", new Date());
            this.rocketMQTemplate.convertAndSend("tanhua-sso-login", msg);
        } catch (Exception e) {
            LOGGER.error("发送消息出错！", e);
        }

        return isNew + "|" + token;

    }

    public User queryUserByToken(String token) {
        try {
//            String redisTokenKey = "TOKEN_" + token;

            //从redis中获取User数据
//            String cacheData = this.redisTemplate.opsForValue().get(redisTokenKey);

            //从token中获取user数据
            Map<String, Object> body = null;
            try {
                body = Jwts.parser()
                        .setSigningKey(secret)
                        .parseClaimsJws(token)
                        .getBody();
            } catch (Exception e) {
                return null;
            }
          /*  if (StringUtils.isEmpty(body.toString())) {
                return null;
            }*/

            String userJson = MAPPER.writeValueAsString(body);


            // 刷新时间
//            this.redisTemplate.expire(redisTokenKey, 1, TimeUnit.HOURS);
            return MAPPER.readValue(userJson, User.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public Boolean updateNewMobile(Long id, String newPhone) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", newPhone);
        User user = this.userMapper.selectOne(queryWrapper);
        if (user != null) {
            // 改手机号已经存在
            return false;
        }
        user = new User();
        user.setId(id);
        user.setMobile(newPhone);
        return this.userMapper.updateById(user) > 0;
    }

}
